<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>迎客宝</title>
  <link rel="stylesheet" href="./css/element-ui@2.13.2.css">
  <link rel="stylesheet" href="./css/index.css">
</head>

<body>
  <div id="app" class="container">
    <div class="header">注册会员</div>
    <div class="store">品牌分店：{{ bName }}</div>
    <el-form :model="ruleForm" ref="ruleForm" label-position="left" label-width="100px" class="ruleForm">
      <el-form-item label="头像" :class="imageUrl ? 'pd8': ''" prop="headImage">
        <el-upload ref="my-upload" :action="baseUrl + '/small/sys/sts/uploadFile'" :show-file-list="false"
          :on-error="handleError" :on-success="handleSuccess" accept="image/*" :on-progress="beforeAvatarUpload"
          v-loading="loading" :before-upload="beforeUpLoad">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <el-input v-else placeholder="请上传" />
        </el-upload>
      </el-form-item>
      <el-form-item label="称呼" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-date-picker type="date" placeholder="请选择" v-model="ruleForm.birthday" value-format="yyyy-MM-dd"
          style="width: 100%;" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="ruleForm.sex" placeholder="请选择">
          <el-option label="男" :value="1"></el-option>
          <el-option label="女" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机" prop="telephone">
        <el-input v-model="ruleForm.telephone" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="邮箱" class="greyColor" prop="mail">
        <el-input v-model="ruleForm.mail" placeholder="选填" />
      </el-form-item>
      <el-form-item label="所在小区" class="greyColor" prop="quarters">
        <el-input v-model="ruleForm.quarters" placeholder="选填" />
      </el-form-item>
      <el-form-item label="推荐人" class="greyColor" prop="recommend">
        <el-input v-model="ruleForm.recommend" placeholder="选填" />
      </el-form-item>
    </el-form>
    <div class="tips">
      温馨提醒：您的信息仅发送该门店用于改善服务和内部管
      理。该店将对您的注册信息安全负责。您与店家的交易，
      属于慎重考虑后的自愿行为，与瑞眸无关。注册代表您同
      意该隐私条款。
    </div>
    <div class="btSubmit" @click="submitForm('ruleForm')">提交</div>
  </div>
</body>

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="./js/vue@2.6.11.js"></script>
<script src="./js/element-ui@2.13.2.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/qs/6.9.4/qs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/exif-js"></script>

<script>
  new Vue({
    el: '#app',
    data() {
      return {
        ruleForm: {
          headImage: '', // 头像
          name: '', // 姓名
          birthday: '', // 生日
          sex: '', // 性别 0 女 1 男
          telephone: '', // 手机
          mail: '', // 邮箱
          quarters: '', // 所在小区
          recommend: '', // 推荐人
        }, // 表单
        baseUrl: 'http://47.92.39.76:8091', // 基础地址
        imageUrl: '', // 头像
        bId: '', // 门店id
        bName: '', // 门店名称
        loading: false // 文件是否上传中
      }
    },
    created() {
      let urlParams = {}
      window.location.href.replace(/([^?&=]+)=([^?&=]*)/ig, (a, b, c) => {
        urlParams[b] = c
      })
      this.bId = urlParams.branchId,
      this.bName = decodeURIComponent(urlParams.branchName)
    },
    methods: {
      beforeAvatarUpload(event, file, fileList) {
        console.log(event)
        this.loading = true;
      },
      handleError() {
        this.loading = false;
        alert('头像上传失败');
      },
      // 文件上传操作成功
      handleSuccess(res, file) {
        if (res.code === 0) {
          this.imageUrl = res.data;
          setTimeout(() => {
            this.loading = false;
          }, 0);
        }
      },
      // 表单验证
      validateForm() {
        const { name, telephone } = this.ruleForm;
        if (!this.imageUrl) {
          alert('头像必传!');
          return false;
        }
        if (!name) {
          alert('称呼必填!');
          return false;
        }
        if (!telephone) {
          alert('手机号码必填!');
          return false;
        }
        if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(telephone))) {
          alert("手机号码有误，请重填!");
          return false;
        }
        return true;
      },
      // 提交表单
      submitForm(formName) {
        if (this.validateForm()) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              let params = { ...this.ruleForm };
              params.headImage = this.imageUrl;
              let qs = Qs;
              axios({
                method: 'post',
                url: this.baseUrl + '/app/shop/member/h5add/' + this.bId,
                headers: { 'content-type': 'application/x-www-form-urlencoded' },
                responseType: 'json',
                data: qs.stringify(params)
              })
                .then(res => {
                  if (res.data.code === 0) {
                    alert(res.data.message);
                    this.$refs['ruleForm'].resetFields();
                    this.imageUrl = '';
                  } else {
                    alert('注册失败！' + res.data.message);
                  }
                });
            } else {
              alert('填写不正确');
              return false;
            }
          });
        }
      },
      beforeUpLoad(file) {
        return new Promise((resolve) => {
          this.getOrientation(file).then((orient) => {
            if (orient && (orient === 6 || orient === 8)) {
              let reader = new FileReader()
              let img = new Image()
              reader.onload = (e) => {
                img.src = e.target.result
                img.onload = () => {
                  const data = this.rotateImage(img, img.width, img.height, orient)
                  const newFile = this.dataURLtoFile(data, file.name)
                  resolve(newFile)
                }
              }
              reader.readAsDataURL(file)
            } else {
              resolve(file)
            }
          })
        })
      },
      getOrientation: (file) => {
        return new Promise((resolve) => {
          EXIF.getData(file, function () {
            const orient = EXIF.getTag(this, 'Orientation')
            resolve(orient)
          })
        })
      },
      dataURLtoFile: (dataurl, filename) => {
        const arr = dataurl.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
      },
      rotateImage: (image, width, height, orient) => {
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        ctx.save()
        canvas.width = height
        canvas.height = width
        if (orient === 6) {
          ctx.rotate(90 * Math.PI / 180)
          ctx.drawImage(image, 0, -height)
        } else {
          ctx.rotate( 270 * Math.PI / 180)
          ctx.drawImage(image, -width, 0)
        }
        ctx.restore()
        return canvas.toDataURL("image/jpeg")
      }
    }
  })
</script>

</html>